package leetcode;

    /**
     * 写两个线程，一个线程打印 1~52，另一个线程打印字母A-Z。
     * 打印顺序为12A34B56C……5152Z。
     * 每个线程单独打印的话肯定没问题，
     * 但是要交替打印，就需要两个线程互相合作，就需要通信。
     * 本质还是生产者消费者，只不过生产者一次生产两个数字，消费者一次消费1个字母
     *
     * @date 2020/3/10 22:59
     */
    public class Code1114_Print2 {
        private final Object LOCK = new Object();
        private volatile boolean produced = false;

        public void produce() throws InterruptedException {
            synchronized (LOCK) {
                for (int i = 1; i <= 52; i++) {
                    if (produced) {
                        LOCK.wait();
                    }
                    System.out.println("生产了:" + i);
                    if (i % 2 == 0) {
                        //生产完毕，通知消费
                        produced = true;
                        LOCK.notifyAll();
                    }
                }
            }
        }

        public void consume() throws InterruptedException {
            synchronized (LOCK) {
                for (int i = 'A'; i <= 'Z'; i++) {
                    if (!produced) {
                        LOCK.wait();
                    }
                    System.out.println("消费了" + (char) i);
                    produced = false;
                    //通知生产
                    LOCK.notifyAll();
                }
            }

        }

        public static void main(String[] args) throws InterruptedException {
            Code1114_Print2 print2 = new Code1114_Print2();
                new Thread(() -> {
                    try {
                        print2.consume();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).start();
                Thread.sleep(50);
                new Thread(() -> {
                    try {
                        print2.produce();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).start();


        }
    }
